import React, { useState } from 'react';
import { Button, Col, Divider, Modal, Row, Space, Tag, Tooltip } from 'antd';
import { Descriptions } from 'antd';
import { Select } from 'antd';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { Card } from 'antd';
import { useEffect } from 'react';
import { getActivityStatus, getdetail } from '@/services/activityInfo';
import JSZip from 'jszip';
import { message } from 'antd';
import FileSaver from 'file-saver';
import { useCallback } from 'react';
import axios from 'axios';
import { AlertTwoTone, BulbOutlined, LikeTwoTone, QuestionCircleOutlined } from '@ant-design/icons';
import { connect, useDispatch } from 'umi';
const ActivityForm: React.FC = (props) => {
  const dispatch = useDispatch();
  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const selectData = [
    { value: '1', label: '1分' },
    { value: '2', label: '2分' },
    { value: '3', label: '3分' },
    { value: '4', label: '4分' },
    { value: '5', label: '5分' },
    { value: '6', label: '6分' },
    { value: '7', label: '7分' },
    { value: '8', label: '8分' },
    { value: '9', label: '9分' },
    { value: '10', label: '10分' },
  ]
  const [messageValue, setMessageValue] = useState('');
  const [selectValue, setSelectValue] = useState('8');
  const [activityDetails, setActivityDetails] = useState<any>();
  const [activityStatus, setActivityStatus] = useState(0)

  /*
  数据处理
  --------------------------------------------------------------------------------------------------
   */
  // 请求文件资源
  const getFile = useCallback((value: string) => {
    let url = "/api/freshSystem/downloadFile/" + value
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url,
        responseType: 'blob',
      }).then((data) => {
        console.log(data)
        resolve(data);
      }).catch((error) => {
        reject(error.toString());
      });

    });
  }, []);
  // 批量下载
  const patchDownload = (value: any) => {
    console.log(value)
    const zip = new JSZip();
    const imgsss: JSZip | null = zip.folder('活动通知');
    const promises: Promise<any>[] = [];
    value.forEach((item) => {
      const promise = getFile(item).then((data: any) => {
        // 下载文件, 文件名
        const file_name = decodeURIComponent(data.headers.get("content-disposition").split('filename=')[1].replace(/"/g, ''));
        // 逐个添加文件
        imgsss?.file(file_name, data.data, { binary: true });
      });
      promises.push(promise);
    });
    Promise.all(promises).then(() => {
      zip.generateAsync({ type: 'blob' }).then((content) => {
        // 生成二进制流,利用file-saver保存文件
        FileSaver.saveAs(content, '活动通知.zip');
      }).catch(() => {
        // 如果有资源文件下载失败，就直接用a链接下载
        message.error("压缩文件下载失败")
      });

    });
  }
  const setFeedBack = (selectValue: any, messageValue: any) => {
    //获取数据接口
    dispatch({
      type: 'Model_Counsellor/setFeedBackEffects',
      payload: {
        activityId: props.activityId,
        stuCode: localStorage.getItem('userAccount'),
        activityImpression: messageValue,
        studentRating: selectValue
      },
    });
  }

  /*
  --------------------------------------------------------------------------------------------------
  数据处理
 */
  /*
  数据请求
  --------------------------------------------------------------------------------------------------
   */
  useEffect(() => {
    if (props.activityId) {
      getdetail(props.activityId).then((response: any) => {
        const activity = response.result;

        // 格式化时间函数
        const formatDate = (datetimeString) => {
          const datetime = new Date(datetimeString);
          const year = datetime.getFullYear();
          const month = (datetime.getMonth() + 1).toString().padStart(2, '0');
          const day = datetime.getDate().toString().padStart(2, '0');
          const hours = datetime.getHours().toString().padStart(2, '0');
          const minutes = datetime.getMinutes().toString().padStart(2, '0');
          const seconds = datetime.getSeconds().toString().padStart(2, '0');
          return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
        };

        // 格式化 endTime
        activity.endTime = formatDate(activity.endTime);

        // 格式化 registrationDeadline
        activity.registrationDeadline = formatDate(activity.registrationDeadline);

        // 格式化 startTime
        activity.startTime = formatDate(activity.startTime);
        if (activity.activityLevel == 0 || activity.activityLevel == "0") activity.activityLevel = "国家级"
        else if (activity.activityLevel == 1 || activity.activityLevel == "1") activity.activityLevel = "省级"
        else if (activity.activityLevel == 2 || activity.activityLevel == "2") activity.activityLevel = "校级"
        else if (activity.activityLevel == 3 || activity.activityLevel == "3") activity.activityLevel = "院级"
        if (activity.activityCategory == 0 || activity.activityCategory == "0") activity.activityCategory = "活动竞赛"
        else if (activity.activityCategory == 1 || activity.activityCategory == "1") activity.activityCategory = "评奖评优"
        else if (activity.activityCategory == 2 || activity.activityCategory == "2") activity.activityCategory = "学生组织"
        setActivityDetails(response.result)
      })
      let data = {
        stuNumber: localStorage.getItem('userAccount'),
        activityId: props.activityId,
      }
      getActivityStatus(data).then((response: any) => {

        console.log(response.result)
        setActivityStatus(response.result)
      })
    }
  }, []); // 空依赖数组确保该 effect 仅在组件挂载时执行一次
  /*
  --------------------------------------------------------------------------------------------------
  数据请求
   */
  return (
    <div>
      <Modal title="活动反馈" style={{ width: '50%' }} open={isFormModalOpen} onOk={() => { setIsFormModalOpen(false), setFeedBack(selectValue, messageValue) }} onCancel={() => setIsFormModalOpen(false)} >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Divider>
            <b>活动打分</b>
            <Tooltip title="请给活动打个分吧！" color={'cyan'} key={1}>
              <LikeTwoTone />
            </Tooltip>
          </Divider>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 30%', width: '100%' }}>
            <a style={{ gridColumn: '1' }} >分数</a>
            <Select defaultValue="8分" allowClear options={selectData} value={selectValue} onChange={setSelectValue} style={{ gridColumn: '2' }} />
          </div>
          <Divider>
            <b>活动感想</b>
            <Tooltip title="写一下本次活动的收获吧！" color={'cyan'} key={1}>
              <AlertTwoTone />
            </Tooltip>
          </Divider>
          <ReactQuill style={{ width: '100%' }} theme="snow" value={messageValue} onChange={setMessageValue} />
        </Space>
      </Modal>
      <Row>
        <Col xl={24} lg={24} md={24} sm={24} xs={24}>
          <Descriptions
            bordered={true}
            column={2}
          >
            <Descriptions.Item label="活动名称">
              {activityDetails?.activityLabel || ''}
            </Descriptions.Item>
            <Descriptions.Item label="举办方">
              {activityDetails?.organizationalUnit || ''}
            </Descriptions.Item>
            <Descriptions.Item label="活动级别">
              {activityDetails?.activityLevel || ''}
            </Descriptions.Item>
            <Descriptions.Item label="活动类型">
              {activityDetails?.activityCategory || ''}
            </Descriptions.Item>
            <Descriptions.Item label="负责人">
              {activityDetails?.teaName || ''}
            </Descriptions.Item>
            <Descriptions.Item label="嘉宾">
              {activityDetails?.guest || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b>举办地点</b>}>
              {activityDetails?.activityAddress || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b>举办日期</b>}>
              {activityDetails?.startTime || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b style={{ color: '#c00000' }}>报名截止日期</b>}>
              {activityDetails?.registrationDeadline || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b style={{ color: '#c00000' }}>活动截止日期</b>}>
              {activityDetails?.endTime || ''}
            </Descriptions.Item>
            <Descriptions.Item
              span={2}
              contentStyle={{
                maxWidth: '80%',
                maxHeight: '80%'
              }}
              label="活动内容"
            >
              {activityDetails?.activityContent || ''}
            </Descriptions.Item>
            <Descriptions.Item label="附件" >
              <a onClick={() => {
                if (activityDetails?.fileId) {
                  const fileList = activityDetails?.fileId.split(",")
                  console.log(fileList)
                  patchDownload(fileList)
                  message.success("下载成功")
                } else {
                  message.warn("文件列表为空")
                }
              }}>下载附件</a>
            </Descriptions.Item>

            <Descriptions.Item label="活动反馈">
              <a onClick={() => {
                if (activityStatus === 2) {
                  setIsFormModalOpen(true)
                } else {
                  message.warn("请等待报名审核通过！")
                }
              }}>活动反馈</a>
            </Descriptions.Item>
          </Descriptions>


        </Col>
      </Row>
    </div>
  );
};

export default connect(({ Model_Counsellor }: any) => ({
  Model_Counsellor,
}))(ActivityForm);
